package product.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.AllArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import product.dto.Gyms;
import product.dto.InvitationCode;
import product.dto.UserGym;
import product.mapper.GymsMapper;
import product.mapper.InvitationCodeMapper;
import product.mapper.UserGymMapper;
import user.params.TypeUpdateDto;
import user.service.UserServiceI;

import java.util.List;

@AllArgsConstructor
@DubboService(version = "1.0.0")
public class GymsServiceImpl implements GymsServiceI {
    private GymsMapper gymsMapper;
    private UserGymMapper userGymMapper;
    private InvitationCodeMapper invitationCodeMapper;
    @DubboReference(version = "1.0.0")
    private UserServiceI userServiceI;


    @Override
    public   String setUserGymByInvitationCode(String invitationCode,int userId) {

        LambdaQueryWrapper<InvitationCode> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(InvitationCode::getCode, invitationCode)
                .eq(InvitationCode::getType, 0);
        InvitationCode invitationCodeDto = invitationCodeMapper.selectOne(queryWrapper);
        if(invitationCodeDto == null){
            return "invitation code is not exist";
        }
        int gymId = invitationCodeDto.getGymId();
        LambdaQueryWrapper<Gyms> gymQueryWrapper = new LambdaQueryWrapper<>();
        gymQueryWrapper.eq(Gyms::getId, gymId);
        Gyms gymDto = gymsMapper.selectOne(gymQueryWrapper);
        if(gymDto == null){
            return "gym is not exist";
        }
        UpdateWrapper<InvitationCode> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(InvitationCode::getCode, invitationCode).set(InvitationCode::getType, 1);
        invitationCodeMapper.update(null, updateWrapper);
        UserGym userGym = new UserGym();
        userGym.setUserId(userId);
        userGym.setGymId(gymId);

        userGymMapper.insert(userGym);
        userServiceI.updateUserType(new TypeUpdateDto(userId, 1));

        return "success";
    }
    @Override
    public List<Gyms> getAllGyms() {
        return gymsMapper.selectList(null);
    }
    @Override
    public List<Gyms> getGymsByUserId(int userId) {
        LambdaQueryWrapper<UserGym> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserGym::getUserId, userId);
        List<UserGym> userGyms = userGymMapper.selectList(queryWrapper);
        List<Integer> gymIds = userGyms.stream().map(UserGym::getGymId).distinct().toList();
        LambdaQueryWrapper<Gyms> gymQueryWrapper = new LambdaQueryWrapper<>();
        gymQueryWrapper.in(Gyms::getId, gymIds);
        return gymsMapper.selectList(gymQueryWrapper);
    }
}
